﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using DTO;
using System.Windows.Forms;

namespace DAO
{
    public class SQLConnectData
    {
        public static SQLConnectData _data = null;
        public static string Server = "(local)";
        private SqlConnection _sqlConnection;

        public SqlConnection SqlConnection
        {
            get { return _sqlConnection; }
            set { _sqlConnection = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        public SQLConnectData()//.\\SQLEXPRESS1
        {
            Connect("Server="+ Server + "; Database = QLNS; Integrated Security = True;");
        }

        public static SQLConnectData DataConnection
        {
            get
            {
                if (_data == null)
                    _data = new SQLConnectData();

                return _data;
            }
        }

        /// <summary>
        /// Ket noi CSDL
        /// </summary>
        /// <param name="data"></param>
        public void Connect(string data)
        {
            try
            {
                _sqlConnection = new SqlConnection(data);
                _sqlConnection.Open();
            }
            catch (Exception)
            {
                MessageBox.Show("Không thể kết nối CSDL!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Dong ket noi CSDL
        /// </summary>
        public void DisConnect()
        {
            if (_sqlConnection.State == System.Data.ConnectionState.Open)
            {
                _sqlConnection.Close();
                _sqlConnection.Dispose();
                _sqlConnection = null;
            }
        }

        /// <summary>
        /// Thuc hien truy van theo stored procedure
        /// </summary>
        /// <param name="st"></param>
        /// <returns></returns>
        public DataTable GetDataFromStoredProcedure(string st)
        {
            SqlConnection cnn = SQLConnectData.DataConnection.SqlConnection;
            SqlCommand cmd = new SqlCommand(st, cnn);
            cmd.CommandType = CommandType.StoredProcedure;

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable table = new DataTable();
            da.Fill(table);

            return table;
        }
    }
}
